<template>
  <div class="container">
    <div class="leftBox">左边</div>
    <div class="formBox">
      <a-form
        ref="formRef"
        :rules="rules"
        class="formBody"
        :model="form"
        :style="{ width: '500px' }"
        @submit="handleSubmit"
      >
        <a-form-item field="username" label="用户名" validate-trigger="blur">
          <a-input v-model="form.username" placeholder="请输入你的用户名" />
        </a-form-item>
        <a-form-item field="password" label="密码" validate-trigger="blur">
          <a-input-password
            v-model="form.password"
            placeholder="请输入你的密码"
          />
        </a-form-item>
        <a-form-item>
          <a-button :loading="loading" type="primary" html-type="submit">
            登录
          </a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import useUserStore from '@/store/modules/user'
import { reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
let form = reactive({
  username: '',
  password: '',
})
let formRef = ref()
// 定义变量控制按钮加载的效果
let loading = ref(false)
let useStore = useUserStore()
//获取路由器
let $router = useRouter()
// 路由对象
let $route = useRoute()

const rules = {
  username: [
    {
      required: true,
      message: '用户名不能为空',
    },
  ],
  password: [
    {
      required: true,
      message: '密码不能为空',
    },
    {
      required: true,
      minLength: 6,
      message: '密码长度必须大于6位数',
    },
  ],
}

const handleSubmit = async () => {
  try {
    const errors = await formRef.value.validate()
    if (errors) {
      // 遍历错误并处理，例如显示错误信息给用户
      for (const field in errors) {
        console.error(
          `Field "${field}" validation failed: ${errors[field].message}`,
        )
        // 这里可以添加代码来显示具体的错误信息到界面上
      }
    } else {
      loading.value = true
      try {
        await useStore.userLogin(form)
        let redirect: any = $route.query.redirect
        $router.push({ path: redirect || '/' })
        // // 登录成功加载效果也消失
        loading.value = false
      } catch (error) {
        loading.value = false
        console.error(error)
      }
    }
  } catch (error) {
    console.error('验证过程中遇到错误', error)
  }
}
</script>

<style lang="scss" scoped>
.container {
  width: 100vw;
  height: 100vh;
  display: flex;
  .leftBox {
    width: $login-left-width;
    height: 100%;
    background-color: azure;
  }
  .formBox {
    width: calc(100vw - $login-left-width);
    height: 100%;
    // background-color: aqua;

    .formBody {
      padding-top: 40px;
      border: 1px solid rgb(233, 230, 230);
      margin: 50vh auto;
      transform: translateY(-50%);
      border-radius: 10px;
    }
  }
}
</style>
